import time
from qturboframe.lib.utils.by import By
from qturboframe.lib.webdriver.exceptions import SeleniumError
from qturboframe.lib.report.log import logger
from qturboframe.public_ui.h_ui.menu import Menu as HuiMenu
from .home_tab import HomeTab
from qturboframe.public_ui.binding_menu_options import binding_menu_vue
from qturboframe.lib.common.web_config import web_config
from .list import List
from BladeFerm.hui12_common.function import display_wait


class Menu(HuiMenu):
    '''
    选择到详细菜单页面。
    '''

    @binding_menu_vue
    def select(self, linkText):
        '''
        反洗钱的产品：菜单栏菜单选择

        :Args:
         - linkText: 菜单栏链接名称集合，按照顺序点击链接

        :Raises:
            SeleniumError: 菜单操作失败
        '''
        try:
            valuelist = linkText.split('/')
            last_menu_name = valuelist[-1]
            # 判断是否有打开的tab，有则全部关闭。（刷新有问题！所以要直接关闭全部，后面重新再打开）
            tab_list = HomeTab(valuelist[-1], idname={By.CSS_SELECTOR: 'div.h-layout-tabbar'},
                               father=self._driver, timeout=1)
            switch_tab_reslut = tab_list.switch_tab(last_menu_name)
            if switch_tab_reslut:
                if len(tab_list.text_tabs) < 10:
                    tab_list.reload()
                    return True
                else:
                    tab_list.close_all()
            # 打开菜单
            for i in range(2):
                self.open_first_and_second_menu(valuelist)
                # 检查菜单是否打开？
                second_tab_name = None
                if '-' in valuelist[-1]:
                    tabs = valuelist[-1].split('-')
                    # second_tab_name = tabs[1]
                    res_flag = self.check_open_menu(tabs[0])
                else:
                    res_flag = self.check_open_menu(valuelist[-1])
                if res_flag:
                    return True
                else:
                    self._driver.refresh()
                    time.sleep(0.5)
                    logger.warning(f'开始第{i+1}次尝试打开菜单！')
            else:
                return SeleniumError(f'尝试打开菜单2次，仍旧失败，请根据失败截图确认原因！')
        except Exception as msg:
            raise SeleniumError(str(msg))

    def open_first_and_second_menu(self, target_menu):
        # 第一级菜单选择
        first_xpath = f'//div[@class="h-layout-menu-item-wrap"]/div/span[contains(text(),"{target_menu[0]}")]'
        first_menu_ul = self._element.find_element_by_attribute(By.XPATH, first_xpath, timeout=self.timeout)
        first_menu_ul.focus()
        first_menu_ul.move_to()
        first_menu_ul.click()
        logger.info('选择第一级菜单：{}'.format(target_menu[0]))
        time.sleep(0.2)
        # 第二级菜单选择
        sec_menu_ele = ('.//body/div[contains(@class,"h-layout-menu-cook-popper-wrap") '
                        'and not(contains(@style,"display: none"))]')
        display_wait(idname={'xpath': sec_menu_ele}, timeout=3, driver=self._driver)
        pop_menu = List({'xpath': sec_menu_ele}, father=self._driver)
        second_menu_name = target_menu[1]
        if '-' in second_menu_name:
            second_menu_name, second_tab_name = second_menu_name.split('-')
        # 修改模糊匹配菜单，解决 客户反洗钱风险等级 菜单名称不一致的情况 --- 20240625
        menu_div = ('.//div[contains(@class,"h-layout-menu-cook-item")]'
                    '/div[contains(@class,"h-layout-menu-cook-item-content")]'
                    f'/span[contains(text(),"{second_menu_name}")]')
        pop_menu.click(idname={'xpath': menu_div})
        logger.info('点击打开第二级菜单：{}'.format(second_menu_name))
        return True

    def check_open_menu(self, name):
        '''
        判断菜单是否已经被打开
        :param name: 菜单名称
        :param page_tabs_list:
        :return:
        '''
        web_config.last_menu = name
        # 确认菜单已经打开
        timeout = 0
        while timeout < self.timeout:
            if HomeTab(name, idname={By.CSS_SELECTOR: 'div.h-layout-tabbar'}, father=self._driver, timeout=1).is_open():
                logger.debug('{} 菜单页已经打开！'.format(name))
                return True
            else:
                timeout = timeout + 0.1
        logger.error(f'{name} 尚未打开，请检查！')
        return False

    def select_third(self, linkText: list):
        '''
        合规的产品：菜单栏菜单选择

        :Args:
         - linkText: 菜单栏链接名称集合，按照顺序点击链接

        :Raises:
            SeleniumError: 菜单操作失败
        '''
        try:
            last_menu_name = linkText[-1]
            # 判断是否有打开的tab，有则全部关闭。（刷新有问题！所以要直接关闭全部，后面重新再打开）
            tab_list = HomeTab(linkText[-1], idname={By.CSS_SELECTOR: 'div.h-layout-tabbar'},
                               father=self._driver, timeout=1)
            switch_tab_result = tab_list.switch_tab(last_menu_name)
            if switch_tab_result and len(tab_list.text_tabs) > 5:
                tab_list.close_others()
            # 打开菜单
            index = 0
            while index < 2:
                index += 1
                self.open_third_menu(linkText)
                # 检查菜单是否打开？
                res_flag = self.check_open_menu(last_menu_name)
                if res_flag:
                    return True
                else:
                    self._driver.refresh()
                    time.sleep(0.5)
                    logger.warning(f'开始第{index}次尝试打开菜单！')
            else:
                return SeleniumError(f'尝试打开菜单2次，仍旧失败，请根据失败截图确认原因！')
        except Exception as msg:
            raise SeleniumError(str(msg))

    def open_third_menu(self, target_menu):
        # 第一级菜单选择
        first_menu_ul_xpath = (f'//div[@class="h-layout-sidebar-body"]//div[@class="h-layout-menu-item-content"]'
                               f'/span[contains(text(),"{target_menu[0]}")]')
        first_menu_ul = self._element.find_element_by_attribute(By.XPATH, first_menu_ul_xpath, timeout=self.timeout)
        first_menu_ul.focus()
        first_menu_ul.move_to()
        first_menu_ul.click()
        logger.info('选择第一级菜单：{}'.format(target_menu[0]))
        time.sleep(0.2)
        # 第二级菜单选择
        sec_menu_ele = '//div[@class="h-layout-menu-cook-side"]'
        right_side = self._element.find_elements_by_attribute(By.XPATH, sec_menu_ele, timeout=2)
        if right_side:
            a_xpath = f'//a[@title="{target_menu[1]}"]'
            right_side_target = right_side[0].find_elements_by_attribute(By.XPATH, a_xpath, timeout=2)
            if right_side_target:
                right_side_target[0].click()
        if len(target_menu) > 2:
            # 修改模糊匹配菜单，解决 客户反洗钱风险等级 菜单名称不一致的情况 --- 20240625
            menu_group_div = (f'//div[contains(@class,"h-layout-menu-cook-group")]//div[contains(@class,"is-title")]'
                              f'//span[contains(text(),"{target_menu[1]}")]'
                              f'//ancestor::div[contains(@class,"h-layout-menu-cook-group")]')
            left_group_side = self._element.find_element_by_attribute(By.XPATH, menu_group_div, timeout=2)
            third_menu_name = f'//div[contains(@class,"h-layout-menu-cook-item-content")]/span[contains(text(),"{target_menu[-1]}")]'
            third_menu = left_group_side.find_element_by_attribute(By.XPATH, third_menu_name, timeout=2)
            third_menu.click()
            logger.info('点击打开第二级菜单：{}'.format('-'.join(target_menu)))
            return True